<?php
/**
 * Create a new Customer
 *
 * @author Xavier VILAIN
 * @package Contact
 *
 */
use Fox\Html\Input;
use Fox\Html\Button;
use Nawa\MedicalStudy\Role;
use Fox\Message;
use Fox\Dao\SqlFragment;
use Fox\Msg;
use Fox\Generator;
use Fox\Html\Header\Image;
use Nawa\Messages;
use Fox\Html\TabPanel\Tab;
use Fox\Html\Wrapper;
use Fox\Html\TabPanel;
use Nawa\Customer;
use Fox\Html\Screen;

$xview = Xview::instance();
try {
	$customer = new Customer($xview->val('customerid'));
	$data = $customer->getData();
	$user = $customer->user();
	$data['documents'] = $customer->documents();
}
catch (Fox\Object\Exception\NotExist $e)
{
	$xview->systemError();
}
$screen = new Screen("eCustomer","update");
$screen->mainTitle(new Image("contact","<div class=\"page-title\">".Msg(Messages::BUNDLE,Messages::TITLE_UPDATE_INVESTIGATOR)."</div>"));
$tabPanel = new TabPanel("pCustomer");
$wMasterData = new Wrapper("wMasterData");

$blName = Xview::instance()->component("customers", "name");
$blName->add(new Fox\Html\DropList(array("role","function"),true,false,true))
->maximize()
->options(Role::all(),'role','label');
$blName->add(new Input(array('employee_service','service'),false));
$wMasterData->add($blName);
$blAddress = Xview::instance()->component("customers", "address");
$blAddress->item("email1")->mandatory();
$wMasterData->add($blAddress);

if(!$data['applicationaccess'] || !$user->authorized())
{
	$data['applicationaccess'] = false;
	$blConnection = Xview::instance()->component("contacts", "user");
	$blConnection->initialize(array("notify" => false));
	$wMasterData->add($blConnection);
}
if($user->authorized())
{
	$screen->add(new Button("remove",null,Msg(User::BUNDLE_NAME,47)))
	->color(Button::COLOR_RED);
}

$blDocuments = Xview::instance()->module(Generator::url("contacts", "documents"));
$wMasterData->add($blDocuments);

$tabPanel->add(new Tab("tMasterData",Msg(Msg::BUNDLE,Msg::TITLE_MASTER_DATA),$wMasterData));
$screen->add($tabPanel);
$screen->initialize($data);
if($screen->submitted())
{
	$inputs = $screen->get();
	// Check Duplicates ?
	if(!$screen->errors())
	{
		$inputs['name1'] = $inputs['first_name'].' '.$inputs['last_name'];
		// Load Customizing Point
		if(isset($inputs['applicationaccess']) && $inputs['applicationaccess'] )
		{
			// Check Mandatory Data
			$input['email1'] = trim($inputs['email1']);
			// Check Duplicates on email
			$finder = new User();
			$res = $finder->find(new SqlFragment("email = ? and idusr != ?",
			array($inputs['email1'],$customer->user()->getId())));
			if(count($res) > 0)
			{
				Message::Error(Msg(Msg::BUNDLE,Msg::ERR_DUPLICATE_USER,$inputs['email1'],$res[0]->fname));
			}
		}
		$finder = new Customer();
		$res = $finder->find(new SqlFragment("email1 = ? and customerid != ?",
		array($inputs['email1'],$customer->getId())),
		null,array(Customer::$JOIN_ADDRESS));
		if(count($res) > 0)
		{
			Message::Error(Msg(Msg::BUNDLE,Msg::ERR_DUPLICATE_USER,$inputs['email1'],$res[0]->name1));
		}
	}

	if(!$screen->errors())
	{
		try {
			// Default Values
			$inputs['type'] = Customer::TYPE_EMPLOYEE;
			// Update Document List
			foreach($customer->documents() as $document) {
				$currentDocList[$document->docid] = $document;
			}
			if(is_array($inputs['documents'])) {
				foreach($inputs['documents'] as $docData) {
					unset($currentDocList[$docData['docid']]);
				}
			}
			if(is_array($currentDocList)) {
				foreach($currentDocList as $document) {
					$customer->deleteFromDocuments($document);
				}
			}
			// Update Contact
			$customer->setFields($inputs);
			$customer->prepareUpdate(Customer::CHANGE_DEFAULT);
			$customer->update();
			$id = $customer->getId();
			// Email Notification
			if(!empty($inputs['notify']) && !empty($inputs['applicationaccess']))
			{
				$customer->user()->notifyCreation(\Xview::instance()->application()->title,_URL_);
				Fox\Message::Success(Msg(Fox\Msg::BUNDLE,Fox\Msg::MSG_NOTIFICATION_MAIL_SENT,$inputs['email1']));
			}
			if($user->authorized() && $screen->buttons('remove')->pushed())
			{
				$application = $customer->user()->application();
				$application->delete();
			}
			
			Fox\Message::Success(Msg(Fox\Msg::BUNDLE,Fox\Msg::MSG_UPDATE,$customer->name1));
			$screen->redirect(Generator::url('contacts','update',null,array('customerid' => $id)));
		}
		catch(Fox\Object\Exception\Save $e)
		{
			//var_dump($e);
			Fox\Message::Error($e->getMessage());
		}
	}

}
echo $screen->Display();